﻿using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
using WeChatSDK.Common;
using WeChatSDK.Common.Enums.Http;
using WeChatSDK.RequestComponent.Http;
using WeChatSDK.WeChatDto.Material;
using WeChatSDK.WeChatDto.Request.Http;
using WeChatSDK.WeChatServiceComponent.Conversation.BaseSupport;

namespace WeChatSDK.WeChatServiceComponent.Material
{
    /// <summary>
    /// 图文素材管理服务
    /// </summary>
    public class NewsMaterialService
    {
        private readonly HttpHandle httpHandle;
        public NewsMaterialService()
        {
            this.httpHandle = new HttpHandle();
        }
        #region 检查内容长度
        /// <summary>
        /// 检查内容长度
        /// </summary>
        /// <param name="materialDto">素材信息</param>
        /// <exception cref="WeChatException"></exception>
        /// <returns></returns>
        public void CheckContentLength(MaterialDto materialDto)
        {
            int maxSize = 0;
            switch (materialDto.FileType)
            {
                case "image":
                    maxSize = 1024 * 1024;
                    break;
                default:
                    break;
            }
            if(materialDto.FileSuffix!=".jpg"&& materialDto.FileSuffix != ".jpeg"&& materialDto.FileSuffix != ".png")
            {
                throw new WeChatException("微信图文素材只允许上传JPG/PNG格式图片，且大小必须小于1M。");
            }
            if(materialDto.FileLength > maxSize)
            {
                throw new WeChatException("微信图文素材只允许上传JPG/PNG格式图片，且大小必须小于1M。");
            }
        }
        #endregion

        #region 新增永久图文素材
        /// <summary>
        /// 新增永久图文素材
        /// </summary>
        /// <param name="newsMaterialDto">图文素材</param>
        /// <returns>{"media_id":MEDIA_ID}</returns>
        public HttpResponseDto AddPermanentNews(NewsMaterialDto newsMaterialDto)
        {
            foreach(var news in newsMaterialDto.Articles)
            {
                //if (news.Content.Length > 20000)
                //{
                //    throw new WeChatException(string.Format("图文 {0} 的内容超出了微信最大字符数2万字符，请优化文章内容。（注：文章字符包括Html标签！）", news.Title));
                //}
                byte[] contentBytes = Encoding.UTF8.GetBytes(news.Content);
                if (contentBytes.Length > 1024 * 1024)
                {
                    throw new WeChatException(string.Format("图文 {0} 的内容超出了微信最大内容容量1M，请优化文章内容。", news.Title));
                }
            }
            //微信图片上传得用WebClient，不可以使用HttpClient
            string url = string.Format("https://api.weixin.qq.com/cgi-bin/material/add_news?access_token={0}", new BaseSupportService().CreateAccessToken().AccessToken);
            Dictionary<string, string> headers = new Dictionary<string, string>();
            headers.Add("Content-Type", "application/json");
            return SendWebRequest(url, Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(newsMaterialDto, WeChatGeneral.JsonSerializerSettings)), headers, MethodType.POST, FormatType.JSON);
        }
        #endregion

        #region 新增永久图文素材
        /// <summary>
        /// 新增永久图文素材(貌似这个可以加小程序)
        /// </summary>
        /// <param name="newsMaterialDto">图文素材</param>
        /// <returns>{"type":"news","media_id":MEDIA_ID,"created_at":1391857799}</returns>
        public HttpResponseDto AddPermanentNewsMedial(NewsMaterialDto newsMaterialDto)
        {
            //微信图片上传得用WebClient，不可以使用HttpClient
            string url = string.Format("https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token={0}", new BaseSupportService().CreateAccessToken().AccessToken);
            Dictionary<string, string> headers = new Dictionary<string, string>();
            headers.Add("Content-Type", "application/json");
            return SendWebRequest(url, Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(newsMaterialDto, WeChatGeneral.JsonSerializerSettings)), headers, MethodType.POST, FormatType.JSON);
        }
        #endregion

        #region 上传图文消息的素材文件
        /// <summary>
        /// 上传图文消息的素材文件
        /// </summary>
        /// <param name="newsMaterialDto">图文素材模型</param>
        /// <returns>{"url":URL}</returns>
        public HttpResponseDto UploadNewsMaterial(MaterialDto materialDto)
        {
            string url = string.Format("https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token={0}", new BaseSupportService().CreateAccessToken().AccessToken);
            Dictionary<string, string> headers = new Dictionary<string, string>();
            headers.Add("Content-Type", string.Format("image/{0}", materialDto.FileSuffix == ".jpg" ? "jpeg" : "png"));
            headers.Add("filename", materialDto.FileName);
            headers.Add("filelength", materialDto.FileLength.ToString());
            return SendWebRequest(url, Encoding.UTF8.GetBytes(materialDto.FullFileName), headers, MethodType.POST, FormatType.FormData);
        }
        #endregion

        #region 修改永久图文素材
        /// <summary>
        /// 修改永久图文素材
        /// </summary>
        /// <param name="mediaId">永久素材Id</param>
        /// <returns>{"errcode":ERRCODE,"errmsg":ERRMSG} 正常情况下调用成功时，errcode将为0。</returns>
        public HttpResponseDto UpdatePermanentNewsMaterial(string mediaId, int index, NewsArticles newsArticles)
        {
            string url = string.Format("https://api.weixin.qq.com/cgi-bin/material/update_news?access_token={0}", new BaseSupportService().CreateAccessToken().AccessToken);
            Dictionary<string, string> headers = new Dictionary<string, string>();
            headers.Add("Content-Type", "application/json");
            return SendWebRequest(url, Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(new { MediaId = mediaId, Index = index, Articles = newsArticles }, WeChatGeneral.JsonSerializerSettings)), headers, MethodType.POST,FormatType.JSON);
        }
        #endregion

        #region 发送WebRequest
        private HttpResponseDto SendWebRequest(string url, byte[] content, Dictionary<string,string> headers, MethodType methodType, FormatType formatType)
        {
            HttpRequestDto httpRequestDto = new HttpRequestDto();
            httpRequestDto.Url = url;
            httpRequestDto.Headers = headers;
            httpRequestDto.Method = methodType;
            httpRequestDto.ContentType = formatType;
            if (content != null && content.Length > 0)
            {
                httpRequestDto.Content = content;
            }
            return httpHandle.WebSendRequest(httpRequestDto);
        }
        #endregion
    }
}
